package online.longzipeng.back.common.config;

/**
 * @Author: lzp
 * @description:
 * @Date: 2022/5/15
 */

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import lombok.extern.slf4j.Slf4j;
import online.longzipeng.back.common.enums.ResponseEnum;
import online.longzipeng.back.common.exception.MessageException;
import online.longzipeng.back.pojo.Result;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.security.SignatureException;

/**
 * 统一异常处理
 */
@Slf4j
@RestControllerAdvice
public class ExceptionHandlerConfig {

    /**
     * 业务异常 统一处理
     */
    @ExceptionHandler(value = MessageException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Object exceptionHandler400(MessageException e) {
        //把错误信息输入到日志中
        log.error(e.getMessage());
        return Result.error(e.getMessage());
    }

    /**
     * 令牌过期
     */
    @ExceptionHandler(ExpiredJwtException.class)
    @ResponseBody
    public Result doExpiredJwtException(ExpiredJwtException e) {
        return new Result(ResponseEnum.TOKEN_TIMEOUT);
    }

    /**
     * token被篡改
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MalformedJwtException.class)
    @ResponseBody
    public Result doMalformedJwtException(MalformedJwtException e) {
        return new Result(ResponseEnum.TOKEN_INVALID);
    }

    /**
     * 秘钥对不上
     *
     * @param e
     * @return
     */
    @ExceptionHandler(SignatureException.class)
    @ResponseBody
    public Result doSignatureException(SignatureException e) {
        return new Result(ResponseEnum.TOKEN_INVALID);
    }


    /**
     * 未知异常 统一处理
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object exceptionHandler(Exception e) {
        //把错误信息输入到日志中
        log.error(e.getMessage());
//        if (log.isDebugEnabled()) {
        e.printStackTrace();
//        }
        return Result.error(e.getMessage());
    }
}
